﻿package com.projects.xenia.add_activities;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.UUID;

import com.projects.xenia.MainSettingsActivity;
import com.projects.xenia.R;
import com.projects.xenia.R.id;
import com.projects.xenia.documents_activities.Activity_OrderList.EfficientAdapter;
import com.projects.xenia.global_modules.MainGlobalModule;
import com.projects.xenia.prompts_activities.Activity_NumericPrompt;
import com.projects.xenia.ref_classes.MessagesRefItem;
import com.projects.xenia.ref_classes.OffersConditionsRefItem;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.TabHost.OnTabChangeListener;

public class Activity_Messages extends Activity {

	private ImageView messages_form_BackWard;
	private ExpandableListView messages_expandablelist;
	private Context Ctx;
	private CustomExpandableListViewAdapter messages_expandablelistAdapter;
	private ArrayList <MessagesRefItem> msg = new ArrayList<MessagesRefItem>();;
	private TabHost tabs;
	
	private void GetMessagesData () {
		
		Cursor MessagesCursor; 
		String where= "";
		
		try {	
		
			switch (tabs.getCurrentTab()) {
			
				case 0:	
					where = "where r.date_read is null";
					break;
					
				case 1:
					where = "where r.date_read is not null";
					break;
					
			}
		
		MessagesCursor = MainGlobalModule.DBE.rawQuery("select m.id, m.message_subject, m.message_body,date (m.date_begin),date (m.date_end),date (r.date_read) from xref_messages m left outer join xdoc_ReadedMessages r on m.id = r.message_id "+where,null);
		
		msg.clear();
		
		if  (MessagesCursor.getCount()>0) {
			MessagesCursor.moveToFirst();			
			while (!MessagesCursor.isAfterLast()){
				MessagesRefItem msgit = new MessagesRefItem ();
				msgit.id = MessagesCursor.getString(0);
				msgit.Message_Subject = MessagesCursor.getString(1);
				msgit.Message_Text = MessagesCursor.getString(2);
				msgit.Date_Begin = MessagesCursor.getString(3);
				msgit.Date_End = MessagesCursor.getString(4);
				msgit.Date_Read = MessagesCursor.getString(5);
				msgit.is_readed = msgit.Date_Read!=null; 
				msg.add(msgit);
				MessagesCursor.moveToNext();
			}
			MessagesCursor.close();
		}
		
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);		
		
		requestWindowFeature(Window.FEATURE_NO_TITLE);            
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);

		setContentView(R.layout.messages_form);
		
		messages_form_BackWard = (ImageView)findViewById(R.id.messages_form_BackWard);
		messages_form_BackWard.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				finish ();
			}
		});
		
		Ctx = this;
		
			
	
		
		tabs = (TabHost) findViewById(android.R.id.tabhost);
		
		tabs.setup();

		TabHost.TabSpec spec;				

		spec = tabs.newTabSpec("tag1");
		spec.setContent(R.id.tab1);
		spec.setIndicator("Новые");
		tabs.addTab(spec);		
		
		spec = tabs.newTabSpec("tag2");
		spec.setContent(R.id.tab1);
		spec.setIndicator("Прочитанные");
		tabs.addTab(spec);
		
		spec = tabs.newTabSpec("tag3");
		spec.setContent(R.id.tab1);
		spec.setIndicator("Все");
		tabs.addTab(spec);
		
		tabs.setCurrentTab(1);
		
		tabs.setOnTabChangedListener(TabChange_Click);
		
		//GetMessagesData ();
		messages_expandablelist = (ExpandableListView)findViewById(R.id.messages_expandablelist);		
		messages_expandablelistAdapter = new CustomExpandableListViewAdapter (this);
		messages_expandablelist.setAdapter(messages_expandablelistAdapter);		
		
		tabs.setCurrentTab(0);
		
		
		messages_expandablelist.setOnItemLongClickListener(new OnItemLongClickListener() {
		@Override
		public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id)  {
				
			int itemType = ExpandableListView.getPackedPositionType(id);				
			if(itemType == ExpandableListView.PACKED_POSITION_TYPE_GROUP) {					
				int groupPosition = ExpandableListView.getPackedPositionGroup(id);
				
				MessagesRefItem it = msg.get(groupPosition);
				
				ContentValues InsUpdValues = new ContentValues();				
				InsUpdValues.put("state",1);
				InsUpdValues.put("date_read",MainGlobalModule.DateToSqlString(Calendar.getInstance().getTime()));				
				 
				if (MainGlobalModule.DBE.update("xdoc_ReadedMessages", InsUpdValues, "message_id=?", new String [] {it.id})==0) {
					InsUpdValues.put("id", UUID.randomUUID().toString().toUpperCase());
					InsUpdValues.put("message_id", it.id);
					InsUpdValues.put("employees_id", MainGlobalModule.SettingsCollection.get("ManagerId"));
					MainGlobalModule.DBE.insert("xdoc_ReadedMessages", null,InsUpdValues);
				}
				
				Toast.makeText(Ctx, "Сообщение помечено как прочитанное !!!", Toast.LENGTH_LONG).show();
				
				GetMessagesData();
				messages_expandablelistAdapter.notifyDataSetChanged();
				
				return true;
			}
			
			return false;
			}
		});
		
		MainGlobalModule.setBackGround(messages_expandablelist);
		
	}
	
	
	private OnTabChangeListener TabChange_Click = new OnTabChangeListener() {		
		@Override
		public void onTabChanged(String tabId) {
			GetMessagesData ();
			messages_expandablelistAdapter.notifyDataSetChanged();
		}
	};
	
	private class CustomExpandableListViewAdapter extends BaseExpandableListAdapter {

		Context context;
		
		public CustomExpandableListViewAdapter (Context context) {
			this.context = context;
		}
		
		@Override
		public MessagesRefItem getChild(int groupPosition, int childPosition) {
			return msg.get(groupPosition);
		}

		@Override
		public long getChildId(int groupPosition, int childPosition) {			
			return 1;
		}

		@Override
		public View getChildView(int groupPosition, int childPosition,boolean isLastChild, View convertView, ViewGroup parent) {

			if (convertView == null) {
	            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	            convertView = inflater.inflate(R.layout.message_body, null);
	        }
			
			MessagesRefItem it = messages_expandablelistAdapter.getGroup(groupPosition);
			
			TextView message_bodytext = (TextView)convertView.findViewById(id.message_bodytext);
			message_bodytext.setText(it.Message_Text);
			
			return convertView;
			
		}

		@Override
		public int getChildrenCount(int groupPosition) {
			return 1;
		}

		@Override
		public MessagesRefItem getGroup(int groupPosition) {			
			return msg.get(groupPosition);
		}

		@Override
		public int getGroupCount() {
			return msg.size();
		}

		@Override
		public long getGroupId(int groupPosition) {			
			return groupPosition;
		}

		@Override
		public View getGroupView(int groupPosition, boolean isExpanded,View convertView, ViewGroup parent) {
			
			
			if (convertView == null) {
	            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	            convertView = inflater.inflate(R.layout.message_subject, null);
	        }
			
			MessagesRefItem it = messages_expandablelistAdapter.getGroup(groupPosition);
			
			ImageView message_status = (ImageView)convertView.findViewById(id.message_status);
			
			if (it.is_readed) {
				message_status.setImageResource(R.drawable.ic_messagereaded);	
			}
			else {
				message_status.setImageResource(R.drawable.ic_messagenew);
			}						
			
			TextView  message_subject = (TextView)convertView.findViewById(id.message_subject);
			message_subject.setText(it.Message_Subject);
			
			TextView  message_details = (TextView)convertView.findViewById(id.message_details);
			message_details.setText(it.Date_Begin);
			
			return convertView;
			
		}

		@Override
		public boolean hasStableIds() {
			// TODO Auto-generated method stub
			return false;
		}

		@Override
		public boolean isChildSelectable(int groupPosition, int childPosition) {
			// TODO Auto-generated method stub
			return false;
		}
				
		
	}
	

		
	
	
	
}
